<?php

namespace app\helpers;

use yii\imagine\Image;
use yii\imagine\Imagine\Image\ManipulatorInterface;

/**
 * 图片处理帮助类
 * Class ImageHelper
 * @package app\helpers
 * @author lv 17.05.16
 * 使用的是图片裁减插件
 * 放置位置:vendor/yiisoft/yii2/imagine
 */

class ImageHelper
{
    /**
     * 裁剪
     * @param $imagePath
     * @param $newImagePath
     * @param $width
     * @param $height
     * @param $start [x, y] 开始位置
     */
    public static function crop($imagePath, $newImagePath, $width, $height, array $start = [0, 0])
    {
        Image::crop($imagePath, $width, $height, $start_array)
            ->save($newImagePath);
    }

    /**
     * 旋转
     * @param        $imagePath
     * @param        $newImagePath
     * @param int    $margin
     * @param string $color
     * @param int    $alpha
     */
    public static function rotate($imagePath, $newImagePath, $margin = 20, $color = '666', $alpha = 100)
    {
        Image::frame($imagePath, $margin, $color, $alpha)
            ->rotate(-8)
            ->save($newImagePath, ['quality' => 50]);
    }

    /**
     * 缩略图（压缩）
     * @param $imagePath
     * @param $newImagePath
     * @param $width
     * @param $height
     */
    public static function thumb($imagePath, $newImagePath, $width, $height)
    {
        Image::thumbnail($imagePath, $width, $height, ManipulatorInterface::THUMBNAIL_OUTBOUND)
            ->save($newImagePath);
    }

    /**
     * 图片水印
     * @param       $imagePath
     * @param       $watermarkPath
     * @param       $newImagePath
     * @param array $start
     */
    public static function watermark($imagePath, $watermarkPath, $newImagePath, array $start = [0, 0])
    {
        Image::watermark($imagePath, $watermarkPath, $start)
            ->save($newImagePath);
    }

    /**
     * 文字水印
     * @param        $imagePath
     * @param        $newImagePath
     * @param        $text
     * @param string $fontFile  the file path or path alias
     * @param array  $start
     * @param array  $fontOptions default value ['size' => '12', 'color' => 'fff', 'angle' => 0]
     */
    public static function text($imagePath, $newImagePath, $text, $fontFile, array $start = [0, 0], array $fontOptions = [])
    {
        Image::text($imagePath, $text, $fontFile, $start, $fontOptions)
            ->save($newImagePath);
    }
}
